//
//  SearchViewController.swift
//  TalkeTv
//
//  Created by lhf on 2024/9/23.
//

import UIKit
import SwiftyJSON
import Toast_Swift
import Alamofire
import AlamofireImage

class SearchViewController: BaseViewController,UITextFieldDelegate {

    var searchArr = JSON.init(parseJSON: "[]")
    @IBOutlet weak var searchView: UIView!
    @IBOutlet weak var searchHeight: NSLayoutConstraint!
    
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var operateView: UIView!
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let courseList = UtilManager.sharedInstance.getVCFromSB(identifier: "CourseListViewController") as! CourseListViewController
        courseList.searchKey = textField.text!
        self.navigationController?.pushViewController(courseList, animated: true)
        return true
    }
    
    // MARK: 获取搜索列表
    func handleGetCourseListData() {
        let params = JSON.init(parseJSON: "{}")
        APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.search_history_action, method: HTTPMethod.get, params: params) { (result, error) in
            if error == nil {
                self.searchArr = result["data"]
                self.reloadSearchView()
            }
        }
    }
    
    // MARK: 更新搜索历史
    func reloadSearchView() {
        operateView.isHidden = searchArr.count == 0
        for view in searchView.subviews {
            view.removeFromSuperview()
        }
    
        let viewHeight: CGFloat = 30
        var x = 0.0
        var y = 0.0
        let padding = 8.0
        let space = 12.0
        let fontSize = 12.0
        
        for i in 0..<searchArr.count {
            
            let textValue = searchArr[i].stringValue
            
            let text:UILabel = UILabel.init()
            text.backgroundColor = UIColor.clear
            text.text = textValue
            text.textAlignment = NSTextAlignment.center
            
            let attributes = [NSAttributedString.Key.foregroundColor: AppConfig.sharedInstance.MAIN_TITLE_COLOR, NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize)]
            let keyword: NSString = NSString(cString: textValue.cString(using: String.Encoding.utf8)!, encoding: String.Encoding.utf8.rawValue)!
            var length = keyword.boundingRect(with:CGSize.init(width: CGFloat(MAXFLOAT), height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil).size.width
            length = length+padding*2 < viewHeight ? viewHeight-padding*2 : length
            text.frame = CGRect.init(x: padding, y: 0, width: length, height: viewHeight)
            text.attributedText = NSAttributedString(string: textValue, attributes: attributes)
            
            let view:UIView = UIView.init()
            view.layer.masksToBounds = true
            view.layer.cornerRadius = 6
            if (x + length+padding*2 + space > searchView.bounds.size.width) {
                x = 0
                y = y + viewHeight + space
            }
            view.frame = CGRect.init(x: x, y: y, width: length+padding*2, height: viewHeight)
            view.backgroundColor = AppConfig.sharedInstance.MAIN_BG_VIEW_COLOR
            x = x + length+padding*2 + space
            view.addSubview(text)
            
            let btn:UIButton = UIButton.init(type: .custom)
            btn.backgroundColor = UIColor.clear
            btn.frame = view.bounds
            btn.tag = i
            btn.addTarget(self, action: #selector(handleClickSearchItem(_:)), for: .touchUpInside)
            view.addSubview(btn)
            
            searchView.addSubview(view)
            
            // 如果是最后一个
            if i == searchArr.count-1{
                searchHeight.constant = view.frame.size.height+view.frame.origin.y
            }
        }
        
        if searchArr.count == 0 {
            searchHeight.constant = 0
        }
    }
    
    @objc func handleClickSearchItem(_ btn: UIButton) {
        let courseList = UtilManager.sharedInstance.getVCFromSB(identifier: "CourseListViewController") as! CourseListViewController
        courseList.searchKey = searchArr[btn.tag].stringValue
        self.navigationController?.pushViewController(courseList, animated: true)
    }
    
    @IBAction func handleSearch(_ sender: Any) {
        let courseList = UtilManager.sharedInstance.getVCFromSB(identifier: "CourseListViewController") as! CourseListViewController
        courseList.searchKey = textField.text!
        self.navigationController?.pushViewController(courseList, animated: true)
    }
    
    @IBAction func handleDel(_ sender: Any) {
        UIAlertController.init().showAlert(title: "提示", message: "确定删除所有搜索记录？") {
            let params = JSON.init(parseJSON: "{}")
            APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.search_history_del_action, method: HTTPMethod.get, params: params) { (result, error) in
                if error == nil {
                    self.searchArr = JSON.init(parseJSON: "[]")
                    self.reloadSearchView()
                }
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        handleGetCourseListData()
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
